﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Microsoft.Extensions.Options;
using NetTopologySuite.Index.HPRtree;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using org.apache.zookeeper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Net;
using System.Reflection.Metadata;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Interface
{
    public class WB_BuyersReturnInterfaceBusiness : WBInterface_BaseBusiness, IJob_Business, ITransientDependency
    {
        //接口信息
        public Base_InterfaceOption WB_Query { get; set; }
        //产品信息
        public WB_CardsInterfaceBusiness wB_CardsInterface { get; set; }
        public WB_BuyersReturnInterfaceBusiness()
        {
            this.InterfaceName = "WB产品退货";
            //索引字段
            this.MapFields = GetMapField("WB_Query");

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            WB_Query = this.interfaceOption.Where(x => x.OperateType == "WB_Query").First();

            //查询执行前的事件
            this.BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            this.OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //查询执行中的事件
            this.AfterQueryEvent += InterfaceBusiness_AfterQueryEvent;

            //执行非查询请求中的事件
            this.OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

            wB_CardsInterface = new WB_CardsInterfaceBusiness();
        }

        /// <summary>
        /// 执行非查询请求中事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="LX_NoQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, WB_NoQueryEventArgs LX_NoQueryEventArgs)
        {
            //API请求是否成功
            LX_NoQueryEventArgs.Success = LX_NoQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private async void InterfaceBusiness_BeforeQueryEvent(object sender, WB_QueryEventArgs queryEventArgs)
        {
            try
            {
                //获取所有产品列表
                queryEventArgs.CustomData = wB_CardsInterface.Query<Cards>(wB_CardsInterface.WB_Query, wB_CardsInterface.SqlDb);
                queryEventArgs.HttpClient.ContentType = "GET";
                //设置请求头参数
                this.SqlDb._conStrings[0] = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                var auth = this.SqlDb.GetListBySql<Base_ConfigParameter>(@$"SELECT * FROM  Base_ConfigParameter(NOLOCK) WHERE Code='WB'");
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", auth.First().Value);
                queryEventArgs.UrlQuery.Header = new Header() { Headers = headers };
                queryEventArgs.Page.PageSize = 200;
                queryEventArgs.Page.SidIndex_s = "false";
            }
            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }

        /// <summary>
        /// 查询中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, WB_QueryEventArgs queryEventArgs)
        {
            //获取请求的数据
            WB_Return_ReqDTO data = new WB_Return_ReqDTO();
            data.is_archive = queryEventArgs.Page.SidIndex_s;
            data.limit = queryEventArgs.Page.PageSize;
            data.offset = queryEventArgs.Page.PageIndex;
            if (queryEventArgs.Page.SidIndex_s == "false") queryEventArgs.HttpClient.Url = queryEventArgs.HttpClient.Url + $"?is_archive={data.is_archive}&limit={data.limit}&offset={data.offset}";
            else queryEventArgs.HttpClient.Url = queryEventArgs.HttpClient.Url.Replace("false", "true");
            queryEventArgs.reqData = GetJsonData(queryEventArgs.APINodes, queryEventArgs.ParentNode, data);
        }

        /// <summary>
        /// 查询执行后的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_AfterQueryEvent(object sender, WB_QueryEventArgs queryEventArgs)
        {

            try
            {
                //将查询后的数据转换成对应格式的数据
                BuyersReturnDTO result = (BuyersReturnDTO)JsonConvert.DeserializeObject<BuyersReturnDTO>(queryEventArgs.ResultStr);
                //产品信息列表
                List<Cards> prdList = (List<Cards>)queryEventArgs.CustomData;
                foreach (var item1 in result.claims)
                {
                    var prd = prdList.Where(x => x.nmID == item1.nm_id);
                    if (prd != null) item1.vendorCode = prd.First().vendorCode;
                }


                if (result.claims.Count >= queryEventArgs.Page.PageSize)
                {
                    queryEventArgs.Page.PageIndex += queryEventArgs.Page.PageSize;
                }
                else
                {
                    //查询完审核中的单据，再查询审核完成的单据
                    if (queryEventArgs.Page.SidIndex_s == "true")
                    {
                        queryEventArgs.Page.Complete = true;
                    }
                    else
                    {
                        queryEventArgs.Page.SidIndex_s = "true";
                    }
                }
                queryEventArgs.Success = true;
                queryEventArgs.Rows = result.claims;
            }
            catch (Exception ex)
            {
                queryEventArgs.Success = false;
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }

        }

        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {
            //获取报表代码
            List<BuyersReturn> code = await this.QueryAsync<BuyersReturn>(this.WB_Query, SqlDb);

        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
